<template>
    <div class="monitor-dashboard">
    <!-- Grafana面板容器 -->
    <div class="dashboard-container">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <p>正在加载监控面板...</p>
        </div>
        
        <!-- Grafana iframe -->
        <iframe
          v-else
          :src="currentUrl"
          class="grafana-iframe"
          frameborder="0"
          @load="handleIframeLoad"
          @error="handleIframeError"
        ></iframe>
        
        <!-- 错误状态 -->
        <div v-if="hasError" class="error-overlay">
          <el-alert
            title="加载失败"
            type="error"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>无法加载监控面板，可能的原因：</p>
              <ul class="error-reasons">
                <li>网络连接问题</li>
              </ul>
              <el-button type="primary" size="small" @click="retryLoad" style="margin-top: 10px;">
                重试加载
              </el-button>
            </template>
          </el-alert>
        </div>
      </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { 
  Loading, 
  Link, 
  Refresh
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(true)
const hasError = ref(false)
const route = useRoute()

// 从环境变量获取Grafana面板URL，并根据URL参数动态替换cluster
const currentUrl = computed(() => {
  // 从环境变量获取基础URL
  const baseUrl = import.meta.env.VITE_APP_GRAFANA_URL || 'https://shennong-grafana-ft-stage.cdreader.vip/d/bdx1j097hmku8d/seatunnel-e79b91-e68ea7-e99da2-e69dbf?from=now-5m&to=now&var-cluster=seatunnel-ccen&var-instance=$__all&refresh=5s&kiosk=tv&var-id=$__all'
  
  try {
    // 创建URL对象来解析和修改参数
    const url = new URL(baseUrl)
    
    // 如果URL参数中携带了cluster，则替换链接中的cluster参数
    const urlCluster = route.query.cluster
    if (urlCluster) {
      url.searchParams.set('var-cluster', urlCluster)
    }
    
    // 如果URL参数中携带了taskId，则替换链接中的var-id参数
    const taskId = route.query.taskId
    if (taskId) {
      url.searchParams.set('var-id', taskId)
    }
    
    // 添加参数来隐藏Grafana顶部元素，实现全屏效果
    url.searchParams.set('kiosk', 'tv')  // tv模式比普通kiosk模式隐藏更多元素
    url.searchParams.set('hide-menu', 'true')  // 隐藏侧边菜单
    url.searchParams.set('hide-toolbar', 'true')  // 隐藏工具栏
    
    return url.toString()
  } catch (error) {
    // 如果URL格式有问题，使用正则表达式替换
    console.warn('URL解析失败，使用正则表达式替换:', error)
    let finalUrl = baseUrl
    
    // 替换cluster参数
    const urlCluster = route.query.cluster
    if (urlCluster) {
      finalUrl = finalUrl.replace(/var-cluster=[^&]+/, `var-cluster=${urlCluster}`)
    }

    // 添加全屏参数
    finalUrl = finalUrl.replace(/kiosk[^&]*/, 'kiosk=tv')
    if (!finalUrl.includes('hide-menu')) {
      finalUrl += '&hide-menu=true'
    }
    if (!finalUrl.includes('hide-toolbar')) {
      finalUrl += '&hide-toolbar=true'
    }
    
    return finalUrl
  }
})

// 刷新面板
const refreshDashboard = () => {
  loading.value = true
  hasError.value = false
  
  // 重新加载iframe
  const iframe = document.querySelector('.grafana-iframe')
  if (iframe) {
    iframe.src = iframe.src
  }
  
  setTimeout(() => {
    loading.value = false
  }, 1000)
}

// iframe加载完成
const handleIframeLoad = () => {
  loading.value = false
  hasError.value = false
  ElMessage.success('监控面板加载成功')
}

// iframe加载错误
const handleIframeError = () => {
  loading.value = false
  hasError.value = true
  ElMessage.error('监控面板加载失败')
}

// 重试加载
const retryLoad = () => {
  hasError.value = false
  loadDashboard()
}

// 新窗口打开
const openInNewTab = () => {
  window.open(currentUrl.value, '_blank')
}

// 监听cluster参数变化，自动刷新iframe
watch(() => route.query.cluster, (newCluster, oldCluster) => {
  if (newCluster !== oldCluster && !loading.value) {
    console.log('Cluster参数变化，刷新iframe:', oldCluster, '->', newCluster)
    refreshDashboard()
  }
})

// 组件挂载时的初始化
onMounted(() => {
  // 开发环境下输出调试信息
  if (import.meta.env.DEV) {
    console.log('监控页面路由参数:', route.query)
    console.log('环境变量Grafana URL:', import.meta.env.VITE_APP_GRAFANA_URL)
    console.log('最终Grafana URL:', currentUrl.value)
  }
  
  // 延迟加载以显示加载状态
  setTimeout(() => {
    loading.value = false
  }, 1000)
})
</script>

<style scoped>
.monitor-dashboard {
  padding: 0;
  margin: 0;
  background-color: #000;
  height: calc(100vh - 60px);
  width: 100%;
  overflow: hidden;
  position: relative;
}



.dashboard-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  overflow: hidden;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #606266;
}

.loading-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}



.grafana-iframe {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  border: none;
  background-color: #000;
  overflow: hidden;
  
  /* 隐藏所有滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* Internet Explorer 10+ */
}

.grafana-iframe::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Opera */
}

.error-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  max-width: 500px;
  z-index: 10;
}

.error-reasons {
  margin: 8px 0;
  padding-left: 20px;
}

.error-reasons li {
  margin-bottom: 4px;
  color: #606266;
  font-size: 13px;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .monitor-dashboard {
    height: calc(100vh - 50px);
  }
}


</style> 